<?php

require_once("./lib/defaults.php");
require_once("./lib/pluginbase.php");
require_once("./cfg/settings.php");

class LoggerPlugin extends PluginBase
{
	protected $logfile;

	public function __construct()
	{
		global $LOG_FILE;
		global $LOG_KEEP;

		if(is_dir(dirname($LOG_FILE)) === false) mkdir(dirname($LOG_FILE), 0777, true);
		for($i = ($LOG_KEEP - 1); $i >= 0; $i--)
		{
			$num = $i == 0 ? "" : "." . ($i);
			$num2 = "." . ($i + 1);

			if(is_file("$LOG_FILE$num")) rename("$LOG_FILE$num", "$LOG_FILE$num2");
		}
		$this->logfile = fopen($LOG_FILE,"w");
		
	}

	function processRawMessage($time, $msg)
	{
		global $LOG_LEVEL;
		if($LOG_LEVEL <= LOGLEVEL_INFO)
		{
			fwrite($this->logfile, "$time SERVER: $msg");
			if($msg[strlen($msg)-1] != "\n") fwrite($this->logfile, "\n");
		}
	}
	
	function logMsg($priority, $msg)
	{
		global $DATEFORMAT;
		global $LOG_LEVEL;
		
		$time = date($DATEFORMAT);
		if($LOG_LEVEL <= $priority)
		{
			$logtxt = "";
			switch($priority)
			{
				case LOGLEVEL_CRITICAL;
					$logtxt = "CRITICAL";
					break;
				case LOGLEVEL_WARNING;
					$logtxt = "WARNING";
					break;
				case LOGLEVEL_INFO;
					$logtxt = "INFO";
					break;
				default:
					$logtxt = "DEBUG";
					break;
			}

			fwrite($this->logfile, "$time $logtxt: $msg");
			fwrite(STDERR, "$logtxt: $msg");
			if($msg[strlen($msg)-1] != "\n") 
			{
				fwrite(STDERR, "\n");
				fwrite($this->logfile, "\n");
			}
		}
	}
}

registerPlugin("logger", new LoggerPlugin);


